package thinkingInJava.generics.wildcard;

//: generics/Holder.java

public class Holder<T> {
private T value;
public Holder() {}
public Holder(T val) { value = val; }
public void set(T val) { value = val; }
public T get() { return value; }
public boolean equals(Object obj) {
  return value.equals(obj);
}	
public static void main(String[] args) {
  Holder<Apple> Apple = new Holder<Apple>(new Apple());
  Apple d = Apple.get();
  Apple.set(d);
  // Holder<Fruit> Fruit = Apple; // Cannot upcast
  Holder<? extends Fruit> fruit = Apple; // OK
  Fruit p = fruit.get();
  d = (Apple)fruit.get(); // Returns 'Object'
  try {
    Orange c = (Orange)fruit.get(); // No warning
  } catch(Exception e) { System.out.println(e); }
  // 因为此时 set 变成了 set(<? extends Fruit> s) <? extends Fruit> 类型的意思是任何继承 Fruit 的事物(page 392)
  // 而编译器无法验证"任何事物"的类型安全性.所以编译不通过
  // fruit.set(new Apple()); // Cannot call set()
  // fruit.set(new Fruit()); // Cannot call set()
  System.out.println(fruit.equals(d)); // OK
}
} /* Output: (Sample)
java.lang.ClassCastException: Apple cannot be cast to Orange
true
*///:~
